import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Observable;

public class UserReceiverConnection extends Observable implements Runnable {
	private ObjectInputStream inputStream;
	private Socket socket;
	private String nickname;
	private boolean stopped;
	
	public UserReceiverConnection(Socket s) {
		super();
		socket = s;
		
		stopped = false;
	}

	@Override
	public void run() {
		
		//Apro lo stream in ingresso
		try {
			this.inputStream = new ObjectInputStream(new BufferedInputStream(
					socket.getInputStream()));
		} catch (IOException e2) {
			setChanged();
			notifyObservers(null);
			stopped = true;
		}
		
		while (inputStream != null && !stopped) {
			try {
				Message receivedMessage = (Message) inputStream.readObject();
				if (receivedMessage != null) {
					setChanged();
					notifyObservers(receivedMessage);
				}
			} catch (IOException e) {
				try {
					inputStream.close();
					setChanged();
					notifyObservers(null);
					stopped = true;
				} catch (IOException e1) {
				}
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public void setNickname(String nickName) {
		this.nickname = nickName;

	}

	public void setStopped() {
		try {
			inputStream.close();
		} catch (IOException e) {
		}
		stopped = true;
	}

	public String getNickname() {
		return nickname;
	}
	
	public Socket getSocket()
	{
		return socket;
	}

}
